<?php
/**
 * Copyright (c) 2009, Jacek Karczmarczyk
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * - Neither the name of the author nor the names of its contributors may be
 *   used to endorse or promote products derived from this software without
 *   specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * PHP Version 5
 *
 * @package Larchana_Application
 * @version 0.1
 * @author Jacek Karczmarczyk <jacek@karczmarczyk.pl>
 */


/**
 * Default bootstrap procedures
 */
class Larchana_Application_Bootstrap_Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
	public function __construct($application)
	{
		parent::__construct($application);
		$this->setContainer(Zend_Registry::getInstance());
	}

	/**
	 * Session initialization and start
	 *
	 */
	protected function _initSession()
	{
		$options = $this->getOption('session');
		if (!is_dir($options['save_path'])) mkdir($options['save_path'], 0777, true);
		Zend_Session::setOptions($options);
	}

	/**
	 * Config initialization
	 *
	 * @return Zend_Config Application configuration
	 */
	protected function _initConfig()
	{
		return new Zend_Config($this->getOptions());
	}

	/**
	 * Cache initialization
	 *
	 * @return Zend_Cache Cache
	 */
	protected function _initCache()
	{
		if (($cacheOptions = $this->getOption('cache')))
		{
			if (!is_dir($cacheOptions['backend']['cache_dir'])) mkdir($cacheOptions['backend']['cache_dir'], 0755, true);
			return Zend_Cache::factory('Core', 'File', $cacheOptions['frontend'], $cacheOptions['backend']);
		}
	}

	/**
	 * Initialization of locale and translation engine
	 *
	 */
	protected function _initTranslate()
	{
		$options = $this->getOption('l10n');
		$translations = array();
		foreach(glob($options['path']."/*".$options['suffix']) as $filename)
		{
			if (file_exists($filename) && is_readable($filename))
			{
				$translations[basename($filename, $options['suffix'])] = $filename;
			}
		}

		if (isset($_GET['__lang']) && array_key_exists($_GET['__lang'], $translations))
		{
			$locale = new Zend_Locale($_GET['__lang']);
			unset($_GET['__lang']);
		}
		else if (array_key_exists('locale', $_COOKIE) && array_key_exists($_COOKIE['locale'], $translations))
		{
			$locale = new Zend_Locale($_COOKIE['locale']);
		}
		else
		{
			$locale = new Zend_Locale();
		}

		if (!array_key_exists($locale->toString(), $translations))
		{
			$locale = new Zend_Locale($options['default']);
		}
		setcookie('locale', $locale->toString(), time()+86400*300, '/');

		Zend_Registry::set('Zend_Locale', $locale);
		Zend_Registry::set('Zend_Translate', 
			new Zend_Translate($options['engine'], $translations[$locale->toString()], $locale->toString())
		);
	}

	/**
	 * Database initialization
	 *
	 * @return Zend_Db Database adapter
	 */
    protected function _initDatabase()
    {
    	$options = $this->getOption('database');
		$database = Zend_Db::factory($options['driver'], $options);
		Zend_Db_Table_Abstract::setDefaultAdapter($database);
		Zend_Db_Table_Abstract::setDefaultMetadataCache($this->getResource('cache'));
		return $database;
    }

    /**
     * Auth initialization
     *
     * @return Zend_Auth Auth object
     */
	protected function _initAuth()
	{
		$config = $this->getOption('auth');
		$auth = Zend_Auth::getInstance();
		if ($auth->hasIdentity())
		{
			$authSession = new Zend_Session_Namespace($auth->getStorage()->getNamespace());
			$authSession->setExpirationSeconds($config['lifetime']);
		}
	}

	/**
	 * Action initialization (action helpers)
	 */
	protected function _initActionHelpers()
	{
		Zend_Controller_Action_HelperBroker::addPrefix('Larchana_Controller_Action_Helper');
		Zend_Controller_Action_HelperBroker::addHelper(new Larchana_Controller_Action_Helper_ErrorMessenger());
		Zend_Controller_Action_HelperBroker::addHelper(new Larchana_Controller_Action_Helper_SuccessMessenger());
	}

	/**
	 * Acl initialization
	 *
	 * Default role for authorized users is "authorized", for not-authorized users is "default"
	 *
	 */
	protected function _initAcl()
	{
		$acl = new Zend_Acl();
		$this->_configureAcl($acl);
		Zend_Registry::set('Zend_Acl', $acl);

		Zend_Controller_Action_HelperBroker::addHelper(new Larchana_Controller_Action_Helper_Acl());
		$helper = Zend_Controller_Action_HelperBroker::getExistingHelper('acl');
		$helper->setRole(Zend_Auth::getInstance()->hasIdentity() ? 'authorized' : 'default');
	}

	/**
	 * Creates roles for ACL object
	 *
	 * @param Zend_Acl $acl Acl object
	 */
	protected function _configureAcl(Zend_Acl $acl)
	{
	}

	/**
	 * View initialization
	 *
	 */
    protected function _initView()
    {
		Zend_Layout::startMvc($this->getOption('layout'));
		$view = new Zend_View($this->getOption('view'));
		$view->setEncoding('UTF-8');
		$view->doctype('HTML5');
		$view->addHelperPath('Larchana/View/Helper', 'Larchana_View_Helper');

		$view->errorMessenger()->enableTranslation();
		$view->successMessenger()->enableTranslation();
		$view->headTitle()->enableTranslation();

		Zend_Controller_Action_HelperBroker::addHelper(
			new Zend_Controller_Action_Helper_ViewRenderer($view, $this->getOption('view'))
		);
    }
}